<template>
	<el-button type="primary" :icon="Plus" circle @click="onClick"> </el-button>
</template>

<script setup lang="ts">
// 添加按钮
// 注意这个只能在 el-form-item绑定为数组的里面使用，不要放到内部的 el-form-item 里面去了
import { Plus } from '@element-plus/icons-vue'
import { isArray } from '@/utils/is'
import { FormItemProps } from '../../../interface'
import { useTrigger } from '@/utils/validate/validatorRules'
const props = withDefaults(
	defineProps<{
		arrayItemProp: Partial<FormItemProps>
		list: Record<string, any>
		index?: number
	}>(),
	{}
)
const { emitTrigger } = useTrigger()
function onClick() {
	const list = props.list
	const index = props.index
	const { compType, itemInfo, compDefault: arrItemDefault } = props.arrayItemProp
	const isObjectItem = isArray(itemInfo)
	// 添加并赋值默认值
	let data = null
	if (isObjectItem) {
		// 对象
		data = itemInfo.reduce((pre, cv) => {
			const { prop, compDefault } = cv
			pre[prop] = compDefault ?? null
			return pre
		}, {} as Record<string, any>)
	} else {
		// 单元素
		const isArray = compType === 'array'
		data = arrItemDefault ?? (isArray ? [] : null)
	}
	if (props.index === undefined) {
		list.push(data)
	} else {
		// 添加到指定下标的上面
		list.splice(index, 0, data)
	}

	// 触发校验
	emitTrigger()
}
</script>
<style scoped lang="scss"></style>
